/**
 * @author ahammer
 * @date  2009 
 */

/*
 * This file is part of Iqm.
 * Copyright (c) 2010-2011 Helmut Ahammer
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package main;

import java.awt.Toolkit;
import java.awt.image.renderable.ParameterBlock;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Vector;

import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

import com.sun.media.jai.codec.TIFFEncodeParam;

/** 
 * 
 * 
 * */
public class SaveStack {
	
	private static File currImgDir;

	public static void run() {
		if (IqmTools.getCurrTankIndex() < 0){
			Board.appendTexln("SaveStack: There aren't any images to save");
			return;
		}
		JFileChooser fc = null;
		//JFileChooser fc = new JFileChooser(System.getProperty("user.dir"));// im eclipse system

		try {fc = new JFileChooser();
		}
		catch (Throwable e) {
			System.out.println("SaveSingle: This plugin requires Java 2 or Swing.");
			return;
		}
	
		fc.setMultiSelectionEnabled(false);
		fc.setDialogType(JFileChooser.SAVE_DIALOG);
		//fc.setDialogType(JFileChooser.);
		fc.setDialogTitle("Save a single image");
		FileNameExtensionFilter filt     = new FileNameExtensionFilter("Image files", "tif", "tiff", "jpg", "jpeg", "png", "bmp");
		FileNameExtensionFilter filtTIFF = new FileNameExtensionFilter("tif", "tif");
		 		
		fc.addChoosableFileFilter(filt);
	    fc.addChoosableFileFilter(filtTIFF);
	    //fc.addChoosableFileFilter(new FileNameExtensionFilter("tif", "*.jpg"));
	    //fc.addChoosableFileFilter(new FileNameExtensionFilter("png", "*.png"));
	    //fc.addChoosableFileFilter(new FileNameExtensionFilter("bmp", "*.bmp"));
	    //fc.setFileFilter(filt);        //default setting
	    fc.setFileFilter(filtTIFF);  //default setting

 
        currImgDir  = IqmTools.getCurrImgPath();
        //System.out.println("Open: " + defaultDir.toString());
		fc.setCurrentDirectory(currImgDir);
	       
		int returnVal = fc.showSaveDialog(fc);
		if (returnVal!=JFileChooser.APPROVE_OPTION) {
			Board.appendTexln("SaveSingle: Error: No image selected");
			return;
		}	
		File file = fc.getSelectedFile();	
		if (file.exists()){
			 Toolkit.getDefaultToolkit().beep();
			 int selected = JOptionPane.showConfirmDialog (null, "File already exists, Overwrite?", "WARNING", JOptionPane.OK_CANCEL_OPTION);
			 if (selected == JOptionPane.CANCEL_OPTION){
				 Board.appendTexln("SaveStack: Image not saved");
				 return;
			 }
		}
		//System.out.println("SaveSingle: fc.getFileFilter().getDescription()" + fc.getFileFilter().getDescription());
		String enc = "default"; //default
		String ext = "default";
		if (file.toString().toLowerCase().endsWith("tif")){
			enc = "TIFF";
			ext = "tif";
			int idx = file.toString().lastIndexOf(".");
			file = new File((String) file.toString().subSequence(0, idx)); //eliminieren der Endung
		}
		if (file.toString().toLowerCase().endsWith("jpg")){
			Board.appendTexln("SaveStack: jpg for singel stack file not allowed, changed to tif");
			enc = "TIFF";
			ext = "tif";
			int idx = file.toString().lastIndexOf(".");
			file = new File((String) file.toString().subSequence(0, idx));
		}
		if (file.toString().toLowerCase().endsWith("png")){
			Board.appendTexln("SaveStack: jpg for singel stack file not allowed, changed to tif");
			enc = "TIFF";
			ext = "tif";
			int idx = file.toString().lastIndexOf(".");
			file = new File((String) file.toString().subSequence(0, idx));
		}
		if (file.toString().toLowerCase().endsWith("bmp")){
			Board.appendTexln("SaveStack: jpg for singel stack file not allowed, changed to tif");
			enc = "TIFF";
			ext = "tif";
			int idx = file.toString().lastIndexOf(".");
			file = new File((String) file.toString().subSequence(0, idx));
		}
		
		//Name ohne extension geschrieben
		if (enc.equals("default")){
				enc = "TIFF";
				ext = "tif";
		}
		boolean virtFlag = false;
	    int index = IqmTools.getCurrTankIndex();
	    if (index == -1) {
		    System.out.println("Tank: no images available");
	    	return;
	    }
		if (Tank.getCurrentTankDataAt(index).firstElement() instanceof PlanarImage) virtFlag = false;
		if (Tank.getCurrentTankDataAt(index).firstElement() instanceof File)        virtFlag = true;  
		int length = Tank.getCurrentTankDataAt(index).getSize();
		System.out.println("SaveStack: Number of images: " + length);
		PlanarImage   pi      = null;
		PlanarImage   piFirst = null;
		Vector<PlanarImage> vec = new Vector<PlanarImage>(length-1);
		for (int n=0; n< length; n++) {			
			if (!virtFlag) pi = (PlanarImage) Tank.getCurrentTankDataAt(index).getElementAt(n);
			if (virtFlag)  pi = JAI.create("fileload", Tank.getCurrentTankDataAt(index).getElementAt(n).toString());
			if (n==0) piFirst = pi;
			if (n>0)  vec.add(n-1, pi);
		}
		String name = file.toString()+"."+ext;
		TIFFEncodeParam param = new TIFFEncodeParam();  
		param.setExtraImages(vec.iterator());
		//param.setCompression(TIFFEncodeParam.COMPRESSION_GROUP4);  
		
		JAI.create("filestore", piFirst, name, "TIFF", param);	
			
		Board.appendTexln("SaveStack: Current stack containg "+length+" images saved to: " +file);
	    
		//set default directory for further processing
		currImgDir = fc.getCurrentDirectory();
		IqmTools.setCurrImgPath(currImgDir);
	
		//Save property to iqm.ini file
		IqmTools.setIqmIniFile("CurrImgPath", currImgDir.toString());
	
	    //Tank.addNewItem(files);
		
	}

}
